<script lang="ts" setup>
import type { IPerson } from "@/myTypes"
import { reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { addPersonApi } from "@/api/person";
import {roles} from "./PersonList.js"

// 组合式api中，给组件声明属性。
const props = defineProps(["adminname"]);

console.log("props.adminname",props.adminname);

interface IEmits{
    (e:"ok"):void
}

// 组合式api中，声明事件
const emit = defineEmits<IEmits>()

const person: IPerson = reactive({});

const ruleFormRef = ref<FormInstance>();

const validatorPass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('Please input 密码'))
    } else {
        // if (!ruleFormRef.value) return;
        // ruleFormRef.value.validateField('password', () => null)      
        if(!(/^[a-z]\w{5}$/.test(value))){
            callback(new Error('密码格式不正确'))
        }
    }
    callback()
}

const rules = reactive<FormRules>({
    adminname: [
        { required: true, message: 'Please input 用户名', trigger: 'blur' }
    ],
    password: [{ validator: validatorPass, trigger: 'blur' }],
    role: [{ required: true, message: 'Please 选择角色', trigger: 'blur' }],
})

// 添加操作人员

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  formEl.validate((valid) => {
    if (valid) {
        person.checkedKeys = "[]";
        addPersonApi(person)
        .then((res:any)=>{
            if(res.data.code=="200"){
                ElMessage({
                    type:"success",
                    message:"添加成功！"
                })
                // 触发事件。
                emit("ok");
            }
        })
    } else {
      console.log('error submit!')
      return false
    }
  })

}

</script>

<template>
    <p>adminname：{{adminname}}</p>
    <el-form ref="ruleFormRef" :model="person" :rules="rules" status-icon label-width="120px" class="demo-ruleForm">
        <el-form-item label="账号名" prop="adminname">
            <el-input v-model="person.adminname" autocomplete="off" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
            <el-input v-model="person.password" autocomplete="off" placeholder="密码格式：共6位，由大小写字母，数字，下划线构成，以小写字母开头" />
        </el-form-item>

        <el-form-item label="角色" prop="role">
            <el-select v-model="person.role">
                <el-option v-for="item in roles" :key="item.value" v-bind="item" />
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">修改</el-button>
            <el-button>Reset</el-button>
        </el-form-item>

    </el-form>
</template>

<style lang="css" scoped></style>
